package com.sakura.mall.generator.util;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据库类型和Java类型转换工具
 */
public class TypeConverter {

    private static final Map<String, String> TYPE_MAP = new HashMap<>();
    
    static {
        // 数值类型
        TYPE_MAP.put("tinyint", "Integer");
        TYPE_MAP.put("smallint", "Integer");
        TYPE_MAP.put("mediumint", "Integer");
        TYPE_MAP.put("int", "Integer");
        TYPE_MAP.put("integer", "Integer");
        TYPE_MAP.put("bigint", "Long");
        TYPE_MAP.put("float", "Float");
        TYPE_MAP.put("double", "Double");
        TYPE_MAP.put("decimal", "BigDecimal");
        TYPE_MAP.put("bit", "Boolean");
        
        // 字符串类型
        TYPE_MAP.put("char", "String");
        TYPE_MAP.put("varchar", "String");
        TYPE_MAP.put("tinytext", "String");
        TYPE_MAP.put("text", "String");
        TYPE_MAP.put("mediumtext", "String");
        TYPE_MAP.put("longtext", "String");
        
        // 日期时间类型
        TYPE_MAP.put("date", "LocalDate");
        TYPE_MAP.put("time", "LocalTime");
        TYPE_MAP.put("datetime", "LocalDateTime");
        TYPE_MAP.put("timestamp", "LocalDateTime");
        
        // 其他类型
        TYPE_MAP.put("blob", "byte[]");
        TYPE_MAP.put("tinyblob", "byte[]");
        TYPE_MAP.put("mediumblob", "byte[]");
        TYPE_MAP.put("longblob", "byte[]");
    }
    
    /**
     * 将数据库类型转换为Java类型
     */
    public static String convertToJavaType(String dbType) {
        dbType = dbType.toLowerCase();
        
        // 处理括号，如 varchar(255) -> varchar
        if (dbType.contains("(")) {
            dbType = dbType.substring(0, dbType.indexOf("("));
        }
        
        String javaType = TYPE_MAP.get(dbType);
        return javaType != null ? javaType : "Object";
    }
    
    /**
     * 获取Java类型对应的导入语句
     */
    public static String getImportByType(String javaType) {
        switch (javaType) {
            case "BigDecimal":
                return "import java.math.BigDecimal;";
            case "LocalDate":
                return "import java.time.LocalDate;";
            case "LocalTime":
                return "import java.time.LocalTime;";
            case "LocalDateTime":
                return "import java.time.LocalDateTime;";
            default:
                return null;
        }
    }
} 